#include <iostream>
#include <stdexcept>
#include <string>

// 自定义异常类
class MyCustomException : public std::runtime_error {
public:
    MyCustomException(const std::string& msg, int errorCode)
        : std::runtime_error(msg), m_errorCode(errorCode) {}

    int errorCode() const { return m_errorCode; }

private:
    int m_errorCode;
};

void functionThatThrows() {
    std::string* ptr = new std::string("This is a potential resource leak");
    // 在抛出异常前，应当处理所有必要的资源释放
    try {
        throw MyCustomException("Custom exception thrown", 101);
    } catch (...) {
        delete ptr; // 确保资源被释放
        throw; // 重新抛出当前的异常
    }
}

int main() {
    try {
        functionThatThrows();
    } 
    catch (const MyCustomException& e) {
        std::cerr << "Caught MyCustomException: " << e.what() 
                  << ", Error Code: " << e.errorCode() << std::endl;
        // 处理特定于自定义异常的逻辑
    }
    catch (const std::exception& e) {
        std::cerr << "Caught std::exception: " << e.what() << std::endl;
        // 处理更一般的异常
    }
    catch (...) {
        std::cerr << "Caught an unknown exception" << std::endl;
        std::set_terminate([]() {
            std::cerr << "Unhandled exception, terminating the program." << std::endl;
            std::abort(); // 强制终止程序
        });
    }
    return 0;
}